<?php
namespace App\Repositories;
use App\Models\Post;
use App\Models\Tag;
use Illuminate\Support\Facades\DB;
class PostRepository extends BaseRepository{
    // a Post instance
    protected $post;

    // a Tag instance
    protected $tag;
    /**
     * create a new PostRepository instance
     * PostRepository constructor.
     * @param $post
     * @param $tag
     */
    public function __construct(Post $post,Tag $tag)
    {
        $this->post = $post;
        $this->tag = $tag;
    }

    /**
     * 获取首页数据
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getIndex(){
        return $this->post->paginate(5);
    }

    /**
     * 后台编辑页面数据
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getPosts(){
        return $this->post->paginate(20);
    }

    /**
     * 获取单个文章的详细数据
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getDetail($id){
        return $this->post->find($id);
    }

    /**
     * save or create a new articles
     * @param $input
     * @param $id
     */
    public function store($input,$id){
        $res = $this->savePost($this->post,$input,$id);
        if($input['tag']){
            $tags = explode(',', substr($input['tag'],strlen($input['tag'])-1,1) === ','?substr($input['tag'],0,-1):$input['tag']);
            $this->tag->where(['post_id'=>$id])->delete();//　更新前，删除多余数据
            foreach ($tags as $item) {
                $this->tag->create(['post_id'=>$id,'label'=>$item,'name'=>$item]);
            }
        }
    }

    /**
     * create of update post
     * @param $model
     * @param $input
     * @param null $post_id
     * @return mixed
     */
    public function savePost($model, $input, $post_id = null){
        if($post_id){
            $model = $model->find($post_id);
        }
        $model->category_id = $input['category'];
        $model->title = $input['title'];
        $model->summary = $input['summary'];
        $model->content = $input['content'];
        $model->view_count = $input['view_count'];
        $model->status = $input['status'];
        $model->save();
        return $model;
    }
}